package cn.wolfcode.blog.service.impl;

import cn.wolfcode.blog.domain.Comment;
import cn.wolfcode.blog.domain.User;
import cn.wolfcode.blog.mapper.CommentMapper;
import cn.wolfcode.blog.service.ICommentService;
import cn.wolfcode.blog.service.IUserService;
import cn.wolfcode.blog.vo.CommentVo;
import cn.wolfcode.blog.vo.ReplyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private IUserService userService;

    @Override
    public void create(ReplyVo vo) {
        // 先判断用户是否存在，若不存在则创建一个
        User user = vo.getUser();
        User userInDb = userService.getById(user.getEmail());
        if (userInDb == null) {
            user.setId(user.getEmail());
            userService.create(user);
        } else {
            user.setId(userInDb.getId());
        }

        // 创建一条评论/回复
        Comment comment = new Comment();
        comment.setParentid(vo.getParentid());
        comment.setContent(vo.getContent());
        comment.setCreatetime(new Date());
        comment.setNum(0);
        comment.setReplyid(vo.getReplyid());
        comment.setReplyname(vo.getReplyname());
        comment.setUserid(user.getId());
        // 保存评论/回复
        commentMapper.insert(comment);
        // 如果是回复（parentid不为空），需要更新parent的回复数量+1
        if (vo.getParentid() != null) {
            Comment commentInDb = commentMapper.selectByPrimaryKey(vo.getParentid());
            commentInDb.setNum(commentInDb.getNum() + 1);
            commentMapper.updateByPrimaryKey(commentInDb);
        }
    }

    @Override
    public List<CommentVo> query() {
        return commentMapper.selectAll();
    }
}
